package com.liuqing.www.文件解析;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
 * 需要包
 * @author 韩世超
 *
 */
public class Property文件解析 {

	private Properties prop;

	private File configFile;

	private long lastModifyTime = 0L;

	private Resource resource;
	
	public void setResource(Resource resource) {
		this.resource = resource;
	}

	private void init() {
		try {
			configFile = resource.getFile();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		prop = new Properties();
		load();
	}

	private void load() {
		try {
			prop.load(new FileInputStream(configFile));
			lastModifyTime = configFile.lastModified();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public Properties getProperties(){
		if ((configFile == null) || (prop == null)) {
			init();
		}
		if (configFile.lastModified() > lastModifyTime) {
			System.err.print("reload config file for lasttime="
					+ lastModifyTime + " and new time="
					+ configFile.lastModified());
		load();
		}
		return prop;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.moloon.sonny.app.Configurable#getConfig(java.lang.String)
	 */
	public String getConfig(String key) {
		if ((configFile == null) || (prop == null)) {
			init();
		}
		if (configFile.lastModified() > lastModifyTime) {
				System.err.print("reload config file for lasttime="
						+ lastModifyTime + " and new time="
						+ configFile.lastModified());
			load();
		}
		return prop.getProperty(key);

	}
	public String toString()
	{
		StringBuffer sb = new StringBuffer();
		Enumeration e = prop.keys();
		while(e.hasMoreElements())
		{
			String key = (String)e.nextElement();
			String value = (String)prop.get(key);
			sb.append("{"+key+"="+value+"}");
		}
		return sb.toString();
	}
	public static void main(String args[]){
		Property文件解析 sl=new Property文件解析();//中文乱码不如自己写
		sl.setResource(new ClassPathResource("/com/liuqing/www/文件解析/area.properties"));
		Map<String,String> areaMap = new HashMap<String, String>();
		
		Properties prop = sl.getProperties();
		for(Object key : prop.keySet()){
			String areaname = (String)key;
			String area = (String)prop.get(key);
			areaMap.put(areaname, area);
		}
	}
}
